package com.chase.framerwork.util;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import net.sf.json.JSONObject;

import org.apache.commons.collections.MapUtils;

/**
 * Map工具类, map,转换成Bean,JSON等.
 * 
 * @Author Chase
 * @Date 2013-10-22
 */
public class MapUtil extends MapUtils
{
	/**
	 * Map为空
	 * 
	 * @param map
	 * @return
	 */
	public static boolean isEmpty(Map<?, ?> map)
	{

		if (map == null || map.isEmpty())
		{
			return true;
		}
		return false;
	}

	/**
	 * Map不为空
	 * 
	 * @param map
	 * @return
	 */
	public static boolean isNotEmpty(Map<?, ?> map)
	{
		return !isEmpty(map);
	}

	/**
	 * Map转换成Bean
	 * 
	 * @param map
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T map2Bean(Map<String, Object> map, Class<T> clazz)
	{
		T t = (T) ReflectionUtil.newObject(clazz);

		Set<Entry<String, Object>> entrySet = map.entrySet();

		for (Entry<String, Object> entity : entrySet)
		{
			String key = entity.getKey();
			Object value = entity.getValue();

			Method[] methods = clazz.getMethods();
			for (Method method : methods)
			{
				if (method.getName().equals(BeanUtil.convertorProperty2SetMethod(key)))
				{
					ReflectionUtil.invokeSetterMethod(t, key, value);
				}
			}
		}

		return t;
	}

	/**
	 * Map转换成JSON对象
	 * 
	 * @param map
	 * @return
	 */
	public static <T> JSONObject map2JSON(Map<String, Object> map)
	{
		return JSONObject.fromObject(map);
	}

	/**
	 * Map转换成JSON格式字符串
	 * 
	 * @param map
	 * @return
	 */
	public static <T> String map2JSONData(Map<String, Object> map)
	{
		return map2JSON(map).toString();
	}
}
